package com.idroc.coelacanth.service.servant;

import java.util.HashMap;
import java.util.Map;

import org.jboss.netty.buffer.ChannelBuffer;

import com.idroc.coelacanth.core.membership.Endpoint;
import com.idroc.coelacanth.core.message.AbstractMessage;

/**
 * 存储服侍器集合响应消息
 * @author yuyoo (yuyoo4j@163.com)
 * @date 2009-12-16 下午05:51:19
 */
public class ServantSetResponseMessage extends AbstractMessage {

	private Endpoint from = null;
	
	private Map<Integer, Endpoint> servants = null;
	
	@Override
	public void decode(ChannelBuffer ib) { 

		from = new Endpoint();
		from.setHost(decodeString(ib));
		from.setPort(ib.readInt());
		
		int size = ib.readInt();
		servants = new HashMap<Integer, Endpoint>();
		for (int i = 0; i < size; i++) {
			int itemNo = ib.readInt();
			Endpoint item = new Endpoint();
			item.setHost(decodeString(ib));
			item.setPort(ib.readInt());
			servants.put(Integer.valueOf(itemNo), item);
		}
	}

	@Override
	public void encode(ChannelBuffer ob) { 
		
		encodeString(ob, from.getHost());
		ob.writeInt(from.getPort());
		
		ob.writeInt(servants.size());
		for (Integer key : servants.keySet()) {
			ob.writeInt(key.intValue());
			Endpoint item = servants.get(key);
			encodeString(ob, item.getHost());
			ob.writeInt(item.getPort());
		}		
	}

	public Endpoint getFrom() {
		return from;
	}

	public void setFrom(Endpoint from) {
		this.from = from;
	}

	public Map<Integer, Endpoint> getServants() {
		return servants;
	}

	public void setServants(Map<Integer, Endpoint> servants) {
		this.servants = servants;
	}

	@Override
	public String toString() {

		StringBuilder sb = new StringBuilder();
		sb.append("ServantSetResponseMessage[");
		sb.append("from:").append(from).append(",");
		sb.append("servants:").append(servants);
		sb.append("]");
		return sb.toString();
	}
}
